import { createServerClient } from '@supabase/ssr'
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

export async function GET(request: NextRequest) {
  const { searchParams, origin } = new URL(request.url)
  const code = searchParams.get('code')
  const next = searchParams.get('next') ?? '/'

  if (code) {
    const supabase = createServerClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
      {
        cookies: {
          get(name: string) {
            return request.cookies.get(name)?.value
          },
          set(name: string, value: string, options: any) {
            // 在这里我们不能设置cookies，因为这是一个GET请求
            // cookies将在重定向后的响应中设置
          },
          remove(name: string, options: any) {
            // 同上
          },
        },
      }
    )

    const { data, error } = await supabase.auth.exchangeCodeForSession(code)

    if (!error && data.user) {
      // 同步用户到数据库
      try {
        await prisma.user.upsert({
          where: { id: data.user.id },
          update: {
            email: data.user.email!,
            name: data.user.user_metadata?.name || data.user.email!,
            avatar: data.user.user_metadata?.avatar_url,
          },
          create: {
            id: data.user.id,
            email: data.user.email!,
            name: data.user.user_metadata?.name || data.user.email!,
            avatar: data.user.user_metadata?.avatar_url,
            role: 'USER',
          },
        })
      } catch (dbError) {
        console.error('Error syncing user to database:', dbError)
      }

      return NextResponse.redirect(`${origin}${next}`)
    }
  }

  // 如果出错，重定向到错误页面
  return NextResponse.redirect(`${origin}/auth/auth-code-error`)
}
